import { viteCommonjs } from '@originjs/vite-plugin-commonjs';
import vue from '@vitejs/plugin-vue';
import vueJsx from '@vitejs/plugin-vue-jsx';
import path from 'path';
import { defineConfig } from 'vite';
import envCompatible from 'vite-plugin-env-compatible';
import VappMeta from './AssetPack/vapp-meta-data.json';
import fse from 'fs-extra';
import externalGlobals from 'rollup-plugin-external-globals'; // --- 引入三方件
import prefixer from 'postcss-prefix-selector';
import autoprefixer from 'autoprefixer';
const configUtil = require('./vapp-helper/configUtil.ts');

function getEnvInfo() {
  let envInfo = {
    env: 'vt3',
    envConf: {
      vt3: {
        baseUrl: '',
      },
    },
  };

  if (process.env.NODE_ENV === 'development' || process.platform === 'win32') {
    // const envUrl = '../public_node_modules/visual_components_web/env.js';
    const envUrl = './vapp-helper/config/envInfo.js';
    envInfo = require(envUrl);
    return envInfo;
  }

  return envInfo;
}

function getAllEnvProxy(proxy, envInfo) {
  const { envConf } = envInfo || {};
  const allProxy = {};

  const excludes = [
    '/recordRules',
    '/codehub',
    '/iamtmp/keystone/auth/getToken',
    '/idp-edit-war',
    '/localApi',
    '/mock',
    '/translateText',
  ];
  Object.entries(envConf).map(([env]) => {
    Object.entries(proxy).map(([i]) => {
      const key = `/${env}${i}`;
      allProxy[key] = {
        target: excludes.includes(i) ? proxy[i].target : envConf[env]?.baseUrl,
        changeOrigin: true,
        secure: false,
        xfwd: false,
        rewrite: _path => _path.replace(new RegExp(`^/${env}`), ''),
      };
    });
  });
  return allProxy;
}

let baseUrl = '';
const envInfo = getEnvInfo();
let codehubUrl = '';
let translateTextApiUrl = '';
if (envInfo) {
  const { env, envConf } = envInfo;
  if (env && envConf) {
    baseUrl = envConf[env].baseUrl;
    codehubUrl = envInfo.codehubUrl;
    translateTextApiUrl = envInfo.translateTextApiUrl;
  }
}

const allProxy = getAllEnvProxy(
  {
    '/api-manager/api/v1/flatten': {
      target: baseUrl,
      changeOrigin: true,
    },
    '/quality': {
      target: baseUrl,
      changeOrigin: true,
    },
    '/indexvapp': {
      target: baseUrl,
      changeOrigin: true,
    },
    '/publici18nservice': {
      target: baseUrl,
      changeOrigin: true,
    },
    '/dcp': {
      target: baseUrl,
      changeOrigin: true,
    },
    '/xtag': {
      target: baseUrl,
      changeOrigin: true,
    },
    '/xvect': {
      target: baseUrl,
      changeOrigin: true,
      timeout: 120000,
    },
    '/xx/xvueapi': {
      target: baseUrl,
      changeOrigin: true,
    },
    '/xvue-admin': {
      target: baseUrl,
      changeOrigin: true,
    },
    '/iam/': {

      // 本地获取token
      target: `${baseUrl}/iam/`,
      changeOrigin: true,
    },
    '/iam/keystone/auth/getToken': {

      // 本地获取token
      target: baseUrl,
      changeOrigin: true,
    },
    '/auth/who': {
      target: baseUrl,
      changeOrigin: true,
    },
    '/localApi': {
      target: 'http://localhost:4000',
      changeOrigin: true,
    },
    '/mock': {
      target: 'http://localhost:4000',
      changeOrigin: true,
    },
    '/codehub': {
      target: codehubUrl,
      changeOrigin: true,
    },
    '/translateText': {
      target: translateTextApiUrl,
      changeOrigin: true,
    },
    '/dcp/data/data': {
      target: baseUrl,
      changeOrigin: true,
    },
  },
  envInfo,
);

const allProxy2 = configUtil.getAllEnvProxy(
  {
    '/auth': {},
    '/quality': {},
    '/dcp': {},
    '/iam': {},
    '/api-manager': {},
  },
);

const config = defineConfig({
  publicDir: '_public', // 给个不存在的目录，防止复制public下不需要的文件到dist文件夹
  define: {
    'process.env.NODE_ENV': process.env.NODE_ENV === 'development' ? JSON.stringify('development') : JSON.stringify('production'),
    'process.env.project_folder': JSON.stringify(path.basename(__dirname)),
    'process.env.xvueNameSpace': JSON.stringify(VappMeta.xvueNameSpace),
    'process.env.xvueNameSpace_': JSON.stringify(`${VappMeta.xvueNameSpace.replace(/-/g, '_')}_`),
    'global': 'window', // 通用地图global报错兼容
  },
  resolve: {
    alias: [
      {
        find: /^~/,
        replacement: '',
      },
      {
        find: '@',
        replacement: path.resolve(__dirname, 'src'),
      },
      {
        find: 'lib',
        replacement: path.resolve(__dirname, 'lib'),
      },
      {
        find: 'public',
        replacement: path.resolve(__dirname, 'public'),
      },
    ],
    extensions: [
      '.mjs',
      '.js',
      '.ts',
      '.jsx',
      '.tsx',
      '.json',
      '.vue',
    ],
  },
  plugins: [
    vue(),
    vueJsx(),
    viteCommonjs(),
    envCompatible(),
  ],
  base: '/',
  css: {
    preprocessorOptions: {
      less: {
        javascriptEnabled: true,
      },
    },
    postcss: {
      plugins: [
        prefixer({
          prefix: `.${VappMeta.xvueNameSpace}`,
          exclude: [`.${VappMeta.xvueNameSpace}`],
          transform(prefix, selector, prefixedSelector, filePath, rule) {
            // 开发环境不执行添加前缀功能
            if (process.env.NODE_ENV === 'development') {
              return selector;
            }
            if (filePath.match(/node_modules/)) {
              return selector; // Do not prefix styles imported from node_modules
            }
            return prefixedSelector;
          },
        }),

        autoprefixer({}), // add options if needed
      ],
    }
  },
  server: {
    strictPort: false,
    port: 8068,
    // host: 'localhost.huawei.com',
    open: true,
    proxy: allProxy2,
  },
  commonjsOptions: {
    esmExternals: true,
  },
  build: {
    target: 'es2015',
    sourcemap: Boolean(envInfo.sourcemap),
    minify: 'esbuild',
    cssCodeSplit: false,
    lib: {
      entry: path.resolve(__dirname, 'src/components/index-design.js'),
      formats: ['es'],
    },
    rollupOptions: {
      external: ['@hw-seq/sweet-ui-base', '@hw-seq/sweet-ui-icons', 'vue', 'element-plus', 'element-plus/es', 'vuex', 'vue-router', 'axios', 'echarts', 'xe-utils', 'vxe-table'],
      output: {
        dir: './AssetPack/web/web-components/lib/design',
        globals: {
          '@hw-seq/sweet-ui-base': 'SweetBase',
          '@hw-seq/sweet-ui-icons': 'SweetUIIcon',
          vue: 'Vue',
          'element-plus': 'ElementPlus',
          'element-plus/es': 'ElementPlus',
          vuex: 'Vuex',
          'vue-router': 'VueRouter',
          axios: 'axios',
          echarts: 'echarts',
          'xe-utils': 'XEUtils',
          'vxe-table': 'VXETable',
        },
        inlineDynamicImports: false,

        entryFileNames: `${VappMeta.xvueNameSpace}.design.js`,
        assetFileNames: `${VappMeta.xvueNameSpace}.design.[ext]`, // css 文件
        chunkFileNames: chunkInfo => {
          const { facadeModuleId, moduleIds, name } = chunkInfo;
          const file = facadeModuleId || moduleIds[moduleIds.length - 1];

          let match;
          match = file.match?.(/\/src\/components\/(.*)\/([^/]+)\.(js|vue)$/);
          if (match) {
            if (`${match[2]}.${match[3]}` === 'index.vue') {
              return `${match[1]}.js`;
            }
          }

          match = file.match?.(/\/src\/(.*)\/([^/]+)\.(js|vue)$/);
          if (match) {
            const dirName = match[1].replace(/\//g, '__').replace('components__', '');
            const fileName = match[2];
            return `${dirName}__${fileName}.js`;
          }

          return `${name}.js`;
        },
      },
      plugins: [
        externalGlobals({
          '@hw-seq/sweet-ui-base': 'SweetBase',
          '@hw-seq/sweet-ui-icons': 'SweetUIIcon',
          vue: 'Vue',
          'element-plus': 'ElementPlus',
          'element-plus/es': 'ElementPlus',
          vuex: 'Vuex',
          'vue-router': 'VueRouter',
          axios: 'axios',
          echarts: 'echarts',
          'xe-utils': 'XEUtils',
          'vxe-table': 'VXETable',
        }),
        {
          name: 'custom-plugin',
          generateBundle(_, bundle) {
            // 搬迁帮助文档
            const targetHelpManualDir = 'AssetPack/web/web-components/lib/help_manual';
            try {
              fse.removeSync(targetHelpManualDir);
            } catch (err) {}
            fse.copy('public/help_manual', targetHelpManualDir);

            // 复制iconfont样式
            fse.copy('public/iconfont', 'AssetPack/web/web-components/lib/iconfont');
          },
        },
      ],
    },
    commonjsOptions: {
      includes: ['node_modules/**/**.js'],
      transfromMixedEsModules: true,
    },
  },
});

export default config;
